package com.ctcemti.mdm.project.sys.controller;

import com.ctcemti.mdm.common.result.Result;
import com.ctcemti.mdm.common.result.ResultEnum;
import com.ctcemti.mdm.common.util.FileUploadUtils;
import com.ctcemti.mdm.common.util.JWTUtil;
import com.ctcemti.mdm.project.sys.service.IOrgStationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.util.StringUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @ClassName CommonController
 * @Description
 * @Author bxf
 * @Date 13:47 2020/2/4
 * @Version V1.0
 **/
@Controller
@RequestMapping("common")
@Api(value = "CommonController", description = "公共文件下载类")
public class CommonController {

    @Value("${ctcemti.errorfilepath}")
    private String errorfilepath;
    @Value("${ctcemti.uploadfilepath}")
    private String uploadfilepath;


    @Autowired
    private IOrgStationService iOrgStationService;

    @ApiOperation(value = "错误数据文件下载")
    @GetMapping("download/downErrorFile")
    @ApiImplicitParams({@ApiImplicitParam(name = "文件原始名称", value = "filename"), @ApiImplicitParam(name = "错误文件信息", value = "errorname"), @ApiImplicitParam(name = "文件类型", value = "type")})
    public void downErrorFile(HttpServletRequest request, HttpServletResponse response, String filename, String errorname, String type) throws Exception {
        String type_self = StringUtil.isEmpty(type) ? ".xls" : type;
        File file = new File(errorfilepath + "/" + filename + type_self);
        FileUploadUtils.downLoadExcel(errorname + type_self, request, response, file);
        file.delete();//文件删除

    }

    @ApiOperation(value = "错误数据文件下载")
    @GetMapping("download/jsfile")
    public void downJsfile(HttpServletRequest request, HttpServletResponse response, String filename, String errorname, String type) throws Exception {
        response.setContentType("text/javascript");

        InputStream is = this.getClass().getClassLoader().getResourceAsStream("static/CTCE/common/js/public.js");
        Resource resource = new ClassPathResource("static/CTCE/common/js/public.js");
        String data = "";
        PrintWriter out = response.getWriter();
        StringBuffer sbf = new StringBuffer();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(resource.getFile()));
            String tempStr;
            while ((tempStr = reader.readLine()) != null) {
                sbf.append(tempStr + " \n  ");
            }
            reader.close();
            System.out.println(sbf.toString());
            byte[] bdata = FileCopyUtils.copyToByteArray(is);
            data = new String(bdata);
            out.println(sbf.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }


    @ApiOperation(value = "验证token是否合法")
    @PostMapping("verificateJWT")
    @ResponseBody
    @ApiImplicitParams({@ApiImplicitParam(name = "token值", value = "accessToken")})
    public Result verificateJWT(HttpServletRequest request, String accessToken) throws Exception {
        boolean flag = JWTUtil.verify(accessToken);
        if (flag) {
            return new Result(ResultEnum.SUCCESS, null);
        } else {
            return new Result(ResultEnum.ZTSJ_1101, null);
        }

    }

    @GetMapping("getImage")
    public void get(String name, HttpServletResponse response) {

        String path = uploadfilepath + File.separator + name;
        //设置ContentType的类型
        String type = "image/" + name.substring(name.lastIndexOf(".") + 1) + ";charset=utf-8";
        FileInputStream inputStream = null;
        OutputStream stream = null;

        try {
            File file = new File(path);
            inputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            inputStream.read(data);
            //setContentType("text/plain; charset=utf-8"); 文本
            response.setContentType(type);
            stream = response.getOutputStream();
            stream.write(data);
            stream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
